<template>
    <div class="user-list">
        <div style="margin: 20px 0">
            <el-select
                v-model="form.typeId"
                style="width: 400px"
                placeholder="请选择类型"
                @change="handleChangeShop"
            >
                <el-option
                    v-for="item in shops"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
            <el-button style="margin: 0 10px" type="primary" @click="addProduct"
                >添加产品</el-button
            >
        </div>
        <el-table :data="products" style="width: 100%">
            <el-table-column prop="id" label="ID" min-width="80" />
            <el-table-column prop="title" label="产品标题" min-width="120" />
            <el-table-column prop="count" label="产品库存" min-width="240" />
            <el-table-column
                prop="productLabel"
                label="产品标签"
                min-width="180"
            >
                <template #default="scope">
                    <div
                        v-for="item in scope.row.product_labels"
                        :key="item.id"
                        style="margin: 8px; display: flex; align-item: center"
                    >
                        <el-tag type="warning">
                            {{ item.name }}
                        </el-tag>
                        <span
                            style="
                                font-size: 14px;
                                padding: 0 10px;
                                color: red;
                                cursor: pointer;
                            "
                            @click="handleDelProductLabel(item.id)"
                            >删除</span
                        >
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="产品价格" min-width="120">
                <template #default="scope">
                    <el-tag type="danger">￥{{ scope.row.price }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="images" label="产品图片" min-width="240">
                <template #default="scope">
                    <img
                        v-if="scope.row.product_images.length"
                        :src="
                            'http://localhost:3000/' +
                            scope.row.product_images[0].url
                        "
                        alt=""
                        style="width: 200px; height: 200px"
                    />
                    <el-tag v-else type="danger">暂未上传logo</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="480">
                <template #default="scope">
                    <el-button
                        type="primary"
                        @click="handleOpenProductImageDialog(scope.row)"
                        >查看产品图
                    </el-button>
                    <el-button
                        type="primary"
                        @click="handleOpenProductLabel(scope.row)"
                        >添加产品标签</el-button
                    >
                    <el-button type="primary" @click="updateProduct(scope.row)"
                        >编辑</el-button
                    >
                    <el-button type="danger" @click="delProduct(scope.row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
            v-model="dialogInfo.visible"
            :title="dialogInfo.title"
            width="30%"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <el-form
                ref="ruleFormRef"
                :model="form"
                :rules="rules"
                label-width="80px"
            >
                <el-form-item label="产品标题" prop="title">
                    <el-input v-model="form.title" />
                </el-form-item>
                <el-form-item label="产品库存" prop="count">
                    <el-input v-model="form.count" type="number" />
                </el-form-item>
                <el-form-item label="产品价格" prop="price">
                    <el-input v-model="form.price" type="number" />
                </el-form-item>
                <el-form-item label="产品详情" prop="detail">
                    <div style="border: 1px solid #ccc; height: 500px">
                        <Toolbar
                            style="border-bottom: 1px solid #ccc"
                            :editor="editorRef"
                            :defaultConfig="toolbarConfig"
                            mode="simple"
                        />
                        <Editor
                            style="height: 320px; overflow-y: hidden"
                            v-model="form.detail"
                            :defaultConfig="editorConfig"
                            mode="simple"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
                <!-- <el-form-item label="产品类型" prop="shopTypeId">
                    <el-select
                        v-model="form.shopTypeId"
                        class="m-2"
                        placeholder="请选择产品类型"
                    >
                        <el-option
                            v-for="item in shopTypes"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)"
                        >确定
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog
            v-model="productImageDialog.visible"
            title="产品图"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            :show-close="false"
            :destroy-on-close="true"
            width="40%"
        >
            <el-upload
                v-model:file-list="productImageDialog.fileList"
                :action="
                    'http://localhost:3000/api/product/image/add?id=' +
                    productImageDialog.uploadData.productId
                "
                :data="productImageDialog.uploadData"
                list-type="picture-card"
                :before-remove="handleProductImageRemove"
            >
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleProductImageCancel"
                        >关闭</el-button
                    >
                </span>
            </template>
        </el-dialog>

        <el-dialog
            v-model="productLabelDialogInfo.visible"
            :title="productLabelDialogInfo.title"
            width="40%"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <el-form :model="productLabelDialogInfo.form" label-width="80px">
                <el-form-item label="产品标签" prop="name">
                    <el-input v-model="productLabelDialogInfo.form.name" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAddProductLabel"
                        >确定
                    </el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, shallowRef } from "vue";
import { list } from "@/api/types";
import {
    add,
    del,
    list as productList,
    update,
    addProductLabel,
    delProductLabel,
} from "@/api/product";

import { ElMessage } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入简介..." };

const editorRef = shallowRef();
const ruleFormRef = ref();

const shops = ref([]);
const products = ref([]);
const shopTypes = ref([]);
const dialogInfo = reactive({
    title: "添加商品分组类型",
    visible: false,
    type: 0,
});

const productLabelDialogInfo = reactive({
    title: "添加产品标签",
    visible: false,
    type: 0,
    form: {
        id: "",
        name: "",
        productId: "",
    },
});

const form = reactive({
    title: "",
    count: "",
    price: "",
    detail: "",
    typeId: "",
    shopTypeId: "",
    id: 0,
});

const productImageDialog = reactive({
    visible: false,
    fileList: [],
    uploadData: { productId: "" },
});

const rules = reactive({
    title: [{ required: true, message: "请输入产品标题", trigger: "blur" }],
    count: [{ required: true, message: "请输入产品数量", trigger: "blur" }],
    price: [{ required: true, message: "请输入产品价格", trigger: "blur" }],
    detail: [{ required: true, message: "请输入产品详情", trigger: "blur" }],
});

onMounted(() => {
    getShops();
});

const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};

const getShops = async () => {
    try {
        const res = await list();
        shops.value = res.result;
        if (shops.value.length) {
            form.typeId = shops.value[0].id;
            shopTypes.value = shops.value[0].shop_types;
            getProducts();
        }
    } catch (err) {
        console.error(err);
    }
};

const getProducts = async (query) => {
    try {
        const res = await productList({ typeId: form.typeId });
        products.value = res.result;
    } catch (err) {
        console.error(err);
    }
};

const handleChangeShop = () => {
    getProducts();
};

const addProduct = () => {
    form.id = "";
    form.title = "";
    form.detail = "";
    form.count = "";
    form.price = "";
    form.shopTypeId = "";
    dialogInfo.type = 0;
    dialogInfo.title = "添加产品";
    dialogInfo.visible = true;
};

const updateProduct = (row) => {
    form.id = row.id;
    form.title = row.title;
    form.detail = row.detail;
    form.count = row.count;
    form.price = row.price;
    form.shopTypeId = row.shopTypeId || "";
    dialogInfo.type = 1;
    dialogInfo.title = "修改产品";
    dialogInfo.visible = true;
};

const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (!dialogInfo.type) {
                await add({
                    title: form.title,
                    detail: form.detail,
                    count: form.count,
                    price: form.price,
                    typeId: form.typeId,
                    shopTypeId: form.shopTypeId || 0,
                });
                ElMessage.success("添加成功");
                resetForm(ruleFormRef.value);
                getProducts();
                return;
            }

            await update(form);
            ElMessage.success("修改成功");
            resetForm(ruleFormRef.value);
            getProducts();
        }
    });
};

const delProduct = async (row) => {
    await del({
        id: row.id,
    });
    ElMessage.success("删除成功");
    getProducts();
};

const handleOpenProductImageDialog = (row) => {
    productImageDialog.uploadData.productId = row.id;
    productImageDialog.fileList = row.product_images.map((ele) => {
        return {
            ...ele,
            url: "http://localhost:8888/img/" + ele.url,
        };
    });
    productImageDialog.visible = true;
};
const handleProductImageCancel = () => {
    productImageDialog.visible = false;

    getProducts();
};

const handleProductImageRemove = async (uploadFile) => {
    try {
        const res = await delMain({ id: uploadFile.id });
        if (res.code !== 200) {
            ElMessage.error("删除失败");
            return false;
        }
        return true;
    } catch (e) {
        console.error(e);
        ElMessage.error("删除失败");
        return false;
    }
};

const handleOpenProductLabel = (row) => {
    productLabelDialogInfo.form.productId = row.id;
    productLabelDialogInfo.visible = true;
};

const handleAddProductLabel = async () => {
    if (!productLabelDialogInfo.form.name) {
        ElMessage.error("标签名称不允许为空");
        return;
    }
    await addProductLabel({
        name: productLabelDialogInfo.form.name,
        productId: productLabelDialogInfo.form.productId,
    });
    ElMessage.success("添加成功");
    productLabelDialogInfo.form.name = "";
    productLabelDialogInfo.visible = false;
    getProducts();
};

const handleDelProductLabel = async (id) => {
    await delProductLabel({ id });
    ElMessage.success("删除成功");
    getProducts();
};

const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
    dialogInfo.visible = false;
};

onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
